<?php
/**
 * News.php
 * 
 * @category    Madoqua
 * @package     Cache
 */

/** zend action */
require_once 'Zend/Cache.php';

require_once 'Madoqua/Exception.php';

/**
 * Madoqua_Cache_News
 * 
 * @category    Madoqua
 * @package     Cache
 */
class Madoqua_Cache_News 
{
    /**
     * the cache
     *
     * @var Zend_Cache_Core
     */
    protected static $_cache;

    /**
     * get the cache
     *
     * @return Zend_Cache_Core
     */
    protected static function getCache()
    {
        if (empty(self::$_cache)) {
            $frontendOptions = array(
                'lifetime' => 3600,
                'automatic_serialization' => true
            );
            $backendOptions = array(
                'cache_dir' => Madoqua_Application::getDataDirectory() . DIRECTORY_SEPARATOR  . 'cache/news/'
            );
            //caching options
            try {
                self::$_cache = Zend_Cache::factory('core', 'file', $frontendOptions, $backendOptions);
                //the cache
            } catch (Exception $e) {
                $exception = new Madoqua_Exception($e->getMessage(), Madoqua_Exception::ERROR);
                $exception->handle();
            }
            
        }
        
        return self::$_cache;
    }    
    
    /**
     * get the feed cache
     * 
     * @param string $url
     * @return Zend_Feed
     */
    public static function get($url) {

        try {
            
            if (!$cache = self::getCache()) {
                throw new Madoqua_Exception('Cannot hit the cache', Madoqua_Exception::CRITICAL);
            }
            //the cache
        
            $id = md5($url);
            //id for the config
        
            $rss = $cache->load($id);
            //try to load it
        
            if ($rss === false) {
            //cache doesn't give us a hit

                Madoqua_Loader::loadModel('Admin_News');
                $rss = Admin_News::build($url);
                    
                $cache->save($rss, $id);
                //and save it
            }
        } catch (Exception $e) {
            $exception = new Madoqua_Exception($e->getMessage(), Madoqua_Exception::ERROR);
            $exception->handle();
            $rss = null;
        }
   
        return $rss;
        //pass it back         
    }
}